/*
 * jxDao Project (2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxDao.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

import org.jxDao.dao.db.DBInfo;
import org.jxUtils.check.ParameterCheck;
import org.jxUtils.file.JXFile;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxDao
 * @package org.jxDao.util
 * @date 27/09/2014 - 09:15:19
 */
public class BackupUtil {
	
	/**
	 * Realiza o backup da Base de Dados do PostgreSQL
	 * 
	 * @param dbInfo
	 * @param backupFile
	 * @param pg_dumpFile
	 * @param replaceFileIfExists
	 * @throws IOException
	 */
	public static final void fromPostgreSQL(final DBInfo dbInfo, final File backupFile, final File pg_dumpFile, final boolean replaceFileIfExists) throws IOException {
	
		ParameterCheck.isNull(dbInfo, "dbInfo");
		ParameterCheck.isNull(backupFile, "backupFile");
		ParameterCheck.isNull(pg_dumpFile, "pg_dumpFile");
		
		//
		if(backupFile.exists()) {
			
			//
			if(replaceFileIfExists) {
				
				backupFile.delete();
				
			}else {
				
				final String baseName = JXFile.getBaseName(backupFile);
				final String extension = JXFile.getFullExtension(backupFile);
				
				new JXFile(backupFile).renameTo(baseName + "_OLD" + extension);
			}
		}
		
		final ProcessBuilder processBuilder = new ProcessBuilder(pg_dumpFile.getAbsolutePath(), "-i", "-h", dbInfo.getHost(), "-p", dbInfo.getPort(), "-U", dbInfo.getUser(), "-F", "c", "-b", "-v", "-f", backupFile.getAbsolutePath(), dbInfo.getDatabase());
		
		processBuilder.environment().put("PGPASSWORD", dbInfo.getPassword());
		
		processBuilder.redirectErrorStream(true);
		
		final Process process = processBuilder.start();
		
		final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
		
		String input = null;
		
		//
		while((input = reader.readLine()) != null) {
			
			System.out.println(input);
		}
		
		reader.close();
	}
}
